<template>
  <div class="create">
    <Header title="生成订单"></Header>
    <van-contact-card
      type="edit"
      :tel="data.tel"
      :name="data.name"
      @click="onEdit"
    />
    <div class="content">
      <div v-for="(item, index) in store.state.orderList" :key="index">
        <van-card
          :num="item.num"
          :price="item.price"
          :title="item.title"
          :thumb="item.pic"
        />
      </div>
    </div>
    <div class="order">
      <div style="padding: 10px">
        <div class="price">
          <span>商品金额</span>
          <span>￥{{ totalPrice }}元</span>
        </div>
        <van-button
          type="primary"
          color="#ffc400"
          class="button"
          @click="goorder"
          >生成订单</van-button
        >
      </div>
    </div>
  </div>
</template>

<script setup>
import Header from "@/components/Header.vue";
import { onMounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import { showDialog } from "vant";
const store = useStore();
const router = useRouter();
const route = useRoute();
const data = ref({
  tel: "13255552558",
  name: "翠花",
});
let totalPrice = ref(0);
// 生成订单总价格
const createPrice = () => {
  let sum = 0;
  store.state.orderList.forEach((item) => {
    sum += item.num * item.price;
  });
  totalPrice.value = sum;
};
// 初始化地址
const initAddress = () => {
  store.state.userAddress.forEach((item) => {
    if (item.isDefault) {
      data.value.name = item.name;
      data.value.tel = item.tel;
    }
  });
};
// 生成订单
const goorder = () => {
  showDialog({
    title: "提示",
    message: "订单生成成功",
  }).then(() => {
    // 要和购物车联系起来(购物车数据选中的商品要剔除，剩下未选中的商品留下)
    const newList = store.state.cartList.filter((item) => {
      // debugger;
      return !route.query.name.includes(item.id + "");
    });
    store.commit("DELETESHOP", newList);
    // 订单数据要拼接上一次的
    store.commit("ORDERLISTEND");
    router.push("/order");
  });
};
function onEdit() {
  router.push("/address");
}
onMounted(() => {
  createPrice();
  initAddress();
});
</script>

<style lang="less" scoped>
.order {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: #fff;
  .price {
    display: flex;
    justify-content: space-between;
    font-size: 16px;
    height: 30px;
    line-height: 30px;
    span:nth-child(2) {
      color: red;
      font-weight: bold;
    }
  }
  .van-button {
    width: 100%;
    margin-top: 5px;
  }
}
</style>
